package com.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.domin.dto.UserInfoDTO;
import com.edu.domin.vo.UserInfoVo;
import com.edu.entity.Article;
import com.edu.entity.User;
import com.edu.entity.UserInfo;
import com.edu.mapper.UserMapper;
import com.edu.properties.MyUserDetails;
import com.edu.service.IArticleService;
import com.edu.service.IUserInfoService;
import com.edu.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 系统用户表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService , UserDetailsService {
    @Autowired
    private IArticleService  articleService;
    @Autowired
    private IUserInfoService userInfoService;
    private static final String email = "123456789@qq.com";
    private static final String image ="https://web-firestwork01.oss-cn-beijing.aliyuncs.com/b49cc52e-03cc-4f81-b9da-95ec8fedfa47.png";
    private static final String phone ="12345678910";
    private static final String address ="中国";

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = query().eq("username", username).one();
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        ArrayList<String> authorities = new ArrayList<>();
        Integer isAdmin = user.getIsAdmin();
        if (isAdmin == 1){
            String role = "admin";
            authorities.add("ROLE_"+role);
        }else{
            String role = "common";
            authorities.add("ROLE_"+role);
            }
        System.out.println("用户" + user.getUsername() + "的权限：" + authorities);
        //自定义myUserDetails，新增字段id
        return new MyUserDetails(user.getUsername(), user.getPassword(),Long.valueOf(user.getId()),
                AuthorityUtils.createAuthorityList(authorities));
    }


    @Override
    public UserInfoVo getinfo(Long id) {
        // 根据id查询用户信息
        User user = query().eq("id", id).one();
        // 根据id查询用户信息
        UserInfo userinfo = userInfoService.query().eq("user_id", id).one();
        // 查文章数据
        List<Article> list = articleService.query().eq("user_id", id).list();
        // 封装数据
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userinfo, vo);

        vo.setId(userinfo.getUserId());
        vo.setName(user.getUsername());
        vo.setEmail(user.getEmail());
        vo.setList(list);

        // 格式化 createdAt 为字符串
            vo.setCreatedAt(user.getCreatedAt());


        return vo;
    }

    @Override
    @Transactional
    public void updateInfo(Long id, UserInfoDTO userInfoDTO) {
        // 更新用户user信息
        User user = getById(id);
        if (userInfoDTO.getUsername() != null) {
            user.setUsername(userInfoDTO.getUsername());
        }
        if (userInfoDTO.getEmail() != null) {
            user.setEmail(userInfoDTO.getEmail());
        }
        // 使用 UpdateWrapper 显式控制更新字段
        QueryWrapper<User> userWrapper = new QueryWrapper<>();
        userWrapper.eq("id", id);
        update(user, userWrapper);

        // 更新用户userinfo信息
        UserInfo userInfo = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", id));
        if (userInfoDTO.getImage() != null) {
            userInfo.setImage(userInfoDTO.getImage());
        }
        if (userInfoDTO.getPhone() != null) {
            userInfo.setPhone(userInfoDTO.getPhone());
        }
        if (userInfoDTO.getAddress() != null) {
            userInfo.setAddress(userInfoDTO.getAddress());
        }
        // 使用 UpdateWrapper 显式控制更新字段
        QueryWrapper<UserInfo> userInfoWrapper = new QueryWrapper<>();
        userInfoWrapper.eq("user_id", id);
        userInfoService.update(userInfo, userInfoWrapper);
    }

    @Override
    public void saveone(User user) {
        user.setEmail(email);
        save(user);
        UserInfo userInfo = new UserInfo();
        userInfo.setImage(image);
        userInfo.setPhone(phone);
        userInfo.setAddress(address);
        userInfo.setUserId(Math.toIntExact(user.getId()));
        userInfoService.save(userInfo);
    }

}

